package com.ali.controller;

import com.ali.common.StringUtil;
import com.ali.dto.*;
import com.ali.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 登录
     */
    @PostMapping(value = "/login")
    public Response<UserInfo> login(@RequestHeader Map<String, Object> header, @RequestBody Map<String, Object> param) {
        log.info("header：" + header);
        log.info("param：" + param);
        String username = StringUtil.getString(param.get("username"));
        String password = StringUtil.getString(param.get("password"));
        try {
            UserInfo userInfo = userService.login(username, password);
            return Response.success(userInfo);
        } catch (Exception e) {
            return Response.fail(ReturnEnum.RC999.getCode(), e.getMessage());
        }
    }

    /**
     * 退出登录
     */
    @PostMapping(value = "/logout")
    public Response<String> logout(@RequestHeader Map<String, Object> header, @RequestBody Map<String, Object> param) {
        log.info("header：" + header);
        log.info("param：" + param);
        String username = StringUtil.getString(header.get("username"));
        try {
            userService.logout(username);
            return Response.success("退出登录成功");
        } catch (Exception e) {
            return Response.fail(ReturnEnum.RC999.getCode(), e.getMessage());
        }
    }

    /**
     * 查询登录记录
     */
    @PostMapping(value = "/login/query")
    public Response<PageInfo<UserLoginInfo>> queryLoginRecord(@RequestHeader Map<String, Object> header, @RequestBody Map<String, Object> param) {
        log.info("header：" + header);
        log.info("param：" + param);
        String pageNo = StringUtil.getString(param.get("pageNo"));
        String pageSize = StringUtil.getString(param.get("pageSize"));
        try {
            PageInfo<UserLoginInfo> pageInfo = userService.queryLoginRecord(pageNo, pageSize);
            return Response.success(pageInfo);
        } catch (Exception e) {
            return Response.fail(ReturnEnum.RC999.getCode(), e.getMessage());
        }
    }
}